<%@ page import="
org.apache.http.util.EntityUtils;,org.apache.http.HttpResponse,org.apache.http.client.methods.HttpPost,org.apache.http.client.methods.HttpGet,org.apache.http.entity.StringEntity,org.apache.http.impl.client.DefaultHttpClient"%>
<%!
	// 操作用户相关
	
	// 环信用户注册带有验证机制
	public Message getHuanxin(String url, Map jsonParam, String header) {
		Message msg = new Message();
		String resData = null;
		try {
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpGet method = new HttpGet(url);
			//StringEntity entity = new StringEntity(GsonUtil.toJson(jsonParam),"utf-8");
			//entity.setContentEncoding("UTF-8");
			//entity.setContentType("application/json");
			//method.setEntity(entity);
			method.addHeader("Authorization", "Bearer " + header);
			HttpResponse result = httpClient.execute(method);
			int code = result.getStatusLine().getStatusCode();
			// 根据环信开发者文档，状态码400说明用户名密码有问题
			if (400 == code) {
				msg =  new Message(400, "访问环信服务器出错");
				resData = EntityUtils.toString(result.getEntity());
				Map map = GsonUtil.fromJson(resData, new TypeToken<Map>(){});
				msg.put("data", map);
				return msg;
			} else {
				// 请求结束，返回结果
				resData = EntityUtils.toString(result.getEntity());
				Map map = GsonUtil.fromJson(resData, new TypeToken<Map>(){});
				msg.put("data", map);
				return msg;
			}
		} catch (Exception e) {
			return new Message(500, "服务器繁忙");
		}
	}

	// 查询群组
	public Message groups(Input input) {
		String GROUPIDURL = "https://a1.easemob.com/eeesys-txby/" + input.getDesc("application") + "/chatgroups";
		input.setDesc("type", "2");
		String server = input.getRequest().getServerName();
		Map param = input.getParameters();
		String json = HttpUtil.encryptPost("http://" + server + ":18088/v2/access_token/get", param);
		Map resMap =  GsonUtil.fromJson(json, new TypeToken<Map>(){});
		Double errcode = (Double)resMap.get("errcode");
		String token = "";
		if (errcode == 20004 || errcode == 20002) {
			json = HttpUtil.encryptPost("http://" + server + ":18088/v2/access_token/create", param);
			resMap =  GsonUtil.fromJson(json, new TypeToken<Map>(){});
			token = Tools.getDesc(resMap.get("access_token"));
		} else {
			token = Tools.getDesc(resMap.get("access_token"));
		}
		Message groupMsg = getHuanxin(GROUPIDURL , param, token);
		if (groupMsg.getErrcode() != 0) {
			return groupMsg;
		}
		List<Map> data = (List<Map>)((Map)groupMsg.get("data")).get("data");
		String groupIds = "";
		for (Map gMap:data) {
			groupIds = groupIds + gMap.get("groupid") + ",";
		}
		groupIds = groupIds.equals("")?"":groupIds.substring(0, groupIds.length() - 1);
		return getHuanxin(GROUPIDURL+ "/" + groupIds , param, token);
	}
%>